import os.path
import re

import requests
from urllib import parse
import pymysql


class ImgesSpider:
    def __init__(self):
        self.imgage_url = 'https://image.baidu.com/search/index?tn=baiduimage&word={}'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}
        self.word = input('请输入关键字')
        self.directory = './images/{}'.format(self.word)
        if not os.path.exists(self.directory):
            os.makedirs(self.directory)
        self.i = 1

    def parse_html(self):
        parmas = parse.quote(self.word)
        html = requests.get(url=self.imgage_url.format(parmas), headers=self.headers).text
        print(html)
        regex = 'thumbURL":"(.*?)"'
        patter = re.compile(regex, re.S)
        # src_list ['http.//','http.//']
        src_list = patter.findall(html)
        for src in src_list:
            print(src)
            self.save_img(src)

    def save_img(self, src):
        html = requests.get(url=src, headers=self.headers).content
        with open('filename', 'wb') as a:
            a.write(html)
        filename = self.directory + '{}_{}.jpg'.format(self.word).format(self.i)
        print(filename, '下载成功')
        self.i += 1

    def run(self):
        self.parse_html()


if __name__ == '__main__':
    spider = ImgesSpider()
    spider.run()
